package com.jn.erp.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Chen Wei
 * @Date: 2022/07/21/10:46
 * @Description:
 */
public class DateUtils {

    public static String getCurrentTime() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(d);
    }

    public static String getCurrentDate1() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(d);
    }
    public static String getCurrentDate() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(d);
    }
    public static String getCurrentMonth() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return sdf.format(d);
    }




    /**
     * 计算两个日期之间相差的天数
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException calendar 对日期进行时间操作
     *                        getTimeInMillis() 获取日期的毫秒显示形式
     */
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 字符串日期格式的计算
     *
     * @param smdate
     * @param bdate
     * @return
     * @throws ParseException
     */
    public static int daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 字符串日期格式和date日期格式的计算
     *
     * @param smdate
     * @param bdate
     * @return
     * @throws ParseException
     */
    public static int daysBetween(String smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    public static  String getLastMonth(Integer i) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        // 设置为当前时间
        calendar.setTime(date);
        // 设置为上一个月
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - i);
        date = calendar.getTime();
        return format.format(date);
    }

    public static  String getLastDay(Integer i) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        // 设置为当前时间
        calendar.setTime(date);
        // i=1 获取明天
        calendar.add(Calendar.DAY_OF_YEAR,i);
        date = calendar.getTime();
        return format.format(date);
    }
    public static  String getLastMonthByDate(String rq) {
        DateFormat format2 =  new SimpleDateFormat("yyyyMM");
        Date date = new Date();
        try{
            date = format2.parse(rq);
        }catch(Exception e){
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        SimpleDateFormat format =  new SimpleDateFormat("yyyyMM");
        c.add(Calendar.MONTH, -1);
        String time = format.format(c.getTime());
        return time;
    }


    //获取本周一的日期
    public static  LocalDate getMon() {
        LocalDate date = LocalDate.now();
        if (date.getDayOfWeek().getValue() == 0){
            date = date.minus(1, ChronoUnit.DAYS);
        }
        // 本周一日期
        date = date.minus(date.getDayOfWeek().getValue() - 1, ChronoUnit.DAYS);
//        LocalDate localSunday = date.minus(date.getDayOfWeek().getValue() - 7, ChronoUnit.DAYS);

        System.out.println("本周一:"+date );
        return date;
    }

    //获取上几周一的日期
    public static  LocalDate getMonByNum(LocalDate date ,int num) {
//        LocalDate date = LocalDate.now();
        date = date.minus(num, ChronoUnit.WEEKS);
        if (date.getDayOfWeek().getValue() == 0){
            date = date.minus(1, ChronoUnit.DAYS);
        }
        // 本周一日期
        date = date.minus(date.getDayOfWeek().getValue() - 1, ChronoUnit.DAYS);
//        LocalDate localSunday = date.minus(date.getDayOfWeek().getValue() - 7, ChronoUnit.DAYS);

        System.out.println("上"+num+"周周一:"+date );
        return date;
    }

    //通过字符串获取LocalDateTime
    public static LocalDateTime getLocalDateTime(String date , String pattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime localDateTime = LocalDateTime.parse(date, dtf);
        return localDateTime;
    }

    //通过LocalDateTime获取字符串
    public static String getString(LocalDateTime date , String pattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        String str = dtf.format(date);
        return str;
    }


    //获取本周几的日期
    public static  LocalDate getWeekDate(int weekDay) {
        LocalDate date = getMon();
        LocalDate localSunday = date.minus(date.getDayOfWeek().getValue() - weekDay, ChronoUnit.DAYS);
        System.out.println( "本周"+weekDay+":"+localSunday);
        return localSunday;
    }


    //获取本月第一天
    public  static LocalDate getMonthFirstDay(){
        // 按月统计
        LocalDate date = LocalDate.now();
        LocalDate firstDate = date.withDayOfMonth(1);
//        // 计算本月
//        LocalDate nextFirstDay = firstDate.minus(-1, ChronoUnit.MONTHS);
        System.out.println("本月1号："+ firstDate);
//        for (int i = 0; i < 5; i++) {
//            firstDate = firstDate.minus(1,ChronoUnit.MONTHS);
//            LocalDate endDate = firstDate.minus(-1,ChronoUnit.MONTHS);
//            System.out.println(firstDate + "****" + endDate);
//        }
        return firstDate;
    }

    //获取本月第几天
    public static  LocalDate getMonthDate(  LocalDate date,int monthDay) {
        LocalDate localSunday = date.minus(1- monthDay, ChronoUnit.DAYS);
        System.out.println( "本y月"+monthDay+"日:"+localSunday);
        return localSunday;
    }


    /**
     * 最近n天的日期字符串
     */
    public static String lastedNDay (String date,int num) {
        LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        LocalDate afterDate = localDate.minusDays(num);

        //获取倒数30天

        List<LocalDate> localDates = new ArrayList<>(num);

        for (LocalDate currentdate = afterDate;
             currentdate.isBefore(localDate) ||
                     currentdate.isEqual(localDate);
             currentdate = currentdate.plusDays(1)) {
            localDates.add(LocalDate.of(currentdate.getYear(), currentdate.getMonth(), currentdate.getDayOfMonth()));
        }
        // 倒叙排列近30天日期
        localDates = localDates.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        StringBuffer stringBuffer = new StringBuffer();
        localDates.stream().forEach(u->stringBuffer.append(u.toString()).append(","));
        String str =stringBuffer.substring(0,stringBuffer.length()-1);
        System.out.println(str);
        return str;
    }

    /**
     * 最近n月的日期字符串
     */
    public static String LastedNMonth (String date,int num) {
        List<String> resultList = new ArrayList<String>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        try {
            Date d = dateFormat.parse(date);
            cal.setTime(d);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //近六个月
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); //要先+1,才能把本月的算进去
        for (int i = 0; i < num; i++) {
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月
            resultList.add(String.valueOf(cal.get(Calendar.YEAR))
                    + "-" + (cal.get(Calendar.MONTH) + 1 < 10 ? "0" +
                    (cal.get(Calendar.MONTH) + 1) : (cal.get(Calendar.MONTH) + 1)));
        }
        StringBuffer stringBuffer = new StringBuffer();
        resultList.stream().forEach(u->stringBuffer.append(u.toString()).append(","));
        String str =stringBuffer.substring(0,stringBuffer.length()-1);
        System.out.println(str);
        return str;
    }
    /**
     * 获取是第几周
     */
    public static String weekNum (String date) {
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date currentDate = null;
        try {
            currentDate = dateFormat.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        // 创建一个Calendar实例
        Calendar calendar = Calendar.getInstance();

        // 将日期设置为当年的第一天
        calendar.set(Calendar.DAY_OF_YEAR, 1);
        // 获取星期几（1表示星期日，2表示星期一，以此类推）
        int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 将日期设置为当前日期
        calendar.setTime(currentDate);
        // 获取一年中的第几天
        int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
        int lastDay = dayOfYear % 7 - firstDayOfWeek;
        int num = lastDay > 0 ? 1 : 0;
        // 计算当前日期是第几周
        int currentWeek = (dayOfYear + (firstDayOfWeek - 1)) / 7 + 1 + num;

        // 输出结果
        System.out.println("当前是第 " + currentWeek + " 周");
        return String.valueOf(currentWeek) ;
    }

    /**
     * 获取上月字符串
     */
    public static String lastMonth (String date) {
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        Date currentDate = null;
        try {
            currentDate = dateFormat.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        // 创建一个Calendar实例
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        // 获取上个月时间
        calendar.add(Calendar.MONTH, -1);

        Date lastMonth = calendar.getTime();
        return dateFormat.format(lastMonth) ;
    }

    /**
     * 获取上月最后一天字符串
     */
    public static String lastMonthLastDay (Date currentDate) {
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        Date currentDate = null;
//        try {
//            currentDate = dateFormat.parse(date);
//        } catch (ParseException e) {
//            throw new RuntimeException(e);
//        }

        // 创建一个Calendar实例
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        // 获取上个月时间
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH,lastDay);
        Date lastMonth = calendar.getTime();
        return dateFormat.format(lastMonth) ;
    }

    public static String getDateFormat(String format) {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(d);
    }

    public static void main(String[] args)  {
//        getMonByNum(1);
        String orderNo = "202410080021";
        orderNo = orderNo.substring(orderNo.length()-4,orderNo.length());
        System.out.println(Integer.parseInt(orderNo));
    }



    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }
}
